<template>
    <a-form ref='formRef' :label-col='{span : 5}' :model='formData'>
        <a-form-item label='excel表' name='file'>
            <a-upload :max-count="1" v-model:file-list='fileList' accept="xls,.xlsx" :beforeUpload='beforeUpload'>
                <template v-if='fileList.length == 0'>
                    <a-button><UploadOutlined />请选择excel表</a-button>
                </template>
            </a-upload>
        </a-form-item>
    </a-form>
</template>

<script lang="ts" setup>
        import { UploadOutlined } from '@ant-design/icons-vue';
        import { nextTick, ref } from 'vue';
        import { importApi } from '@/api/DeptContacts';
        //import Papa from 'papaparse';



        function parseExcelFile(file) {
            return new Promise((resolve, reject) => {


                const reader = new FileReader();

                reader.onload = function (event) {
                    const data = new Uint8Array(event.target.result);
                    const workbook = XLSX.read(data, { type: 'array' });

                    // 获取第一个sheet
                    const sheetName = workbook.SheetNames[0];
                    const worksheet = workbook.Sheets[sheetName];

                    // 解析sheet为JSON
                    const json = XLSX.utils.sheet_to_json(worksheet);

                    // 转换为目标结构
                    const result = parseToStructure(json);
                    resolve(result)
                };

            reader.readAsArrayBuffer(file);


                
            });
        }

 
        function parseToStructure(data) {
    const deptMap = {};
    let currentMainDept = null;
    let currentSubDept = null;

    data.forEach(row => {
        const mainDept = row['主部门']; // 假设列名为 '主部门'
        const subDept = row['子部门'];  // 假设列名为 '子部门'
        const tel = row['电话'];        // 假设列名为 '电话'
        const location = row['校区'];   // 假设列名为 '地址'

        // 如果当前行的主部门为空，则沿用上一行的主部门
        if (mainDept && mainDept.trim()) {
            currentMainDept = mainDept;
            if (!deptMap[currentMainDept]) {
                deptMap[currentMainDept] = {
                    dept: currentMainDept,
                    depts: []
                };
            }
        }

        // 如果当前行的子部门为空，则沿用上一行的子部门
        if (subDept && subDept.trim()) {
            currentSubDept = subDept;
        }

        // 如果有当前主部门和子部门，则进行处理
        if (currentMainDept && currentSubDept) {
            const children = deptMap[currentMainDept].depts;

            // 查找是否已有该子部门
            let childDept = children.find(child => child.dept === currentSubDept);

            // 如果子部门不存在，则新建
            if (!childDept) {
                childDept = {
                    dept: currentSubDept,
                    contacts: []
                };
                children.push(childDept);
            }

            // 向 contacts 数组中添加联系方式
            childDept.contacts.push({ tel, location });
        }
    });

    // 返回格式化的部门列表
    return Object.values(deptMap);
}



    const fileList = ref<any[]>([])

    const formRef = ref()

    
    
    const formData = ref<any>({
        category : '',
        file : ''
    })

    


    async function submit() {
        let params  = await formRef.value.validate()
        

        if(!params.file) {
            return
        }
        const file = params.file

        const data = await parseExcelFile(params.file)
        return importApi(data)
    }


    function beforeUpload(file:File, field:FormField) {
        formData.value.file = file
        return false
    }

    defineExpose({
        submit
    })
</script>